package com.leenleda.ips.net;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class AEvent {

    public static final String NET_REQUEST = "net_request";
    public static final String TO_TOAST = "to_toast";
    public static final String TO_DOWNLOAD = "to_download";
    public static final String CHECK_UPDATE_TOOL = "check_update_tool";     //更新工具开启检查

    private static class EventObj{
        AEventListener listener;
        String eventId;
    }

    private static List<EventObj> eventList = new ArrayList<>();
    private static Handler mHandler;

    public static void setHandler(Handler handler){
        mHandler = handler;
    }

    public static void addListener (String eventId, AEventListener listener){
        for (EventObj event : eventList)
            if (event.eventId.equals(eventId) && event.listener.getClass() == listener.getClass())
                return;
        EventObj event = new EventObj();
        event.listener = listener;
        event.eventId = eventId;
        eventList.add(event);
    }

    public static void removeListener(String eventId, AEventListener listener){
        EventObj event;
        for (int i = 0; i < eventList.size(); i ++){
            event = eventList.get(i);
            if (event.eventId.equals(eventId) && event.listener == listener){
                eventList.remove(i);
                return;
            }
        }
    }

    public static void notifyListener(String eventId, boolean success, Object obj){
        Log.e("SLKVNSDV", "=====eventId===11===" + eventId);
        if (Looper.myLooper() == Looper.getMainLooper()){
            dispatch(eventId, success, obj);
        } else {
            if (mHandler != null){
                mHandler.post(() -> {
                    dispatch(eventId, success, obj);
                });
            } else {
                dispatch(eventId, success, obj);
            }
        }
    }

    private static void dispatch(String eventId, boolean success, Object obj){
        EventObj event;
        for (int i = 0; i < eventList.size(); i++){
            event = eventList.get(i);
            if (event.eventId.equals(eventId))
                event.listener.dispatchEvent(eventId, success, obj);
        }
    }
}
